package com.app.common;
import fr.brouillard.oss.commonmark.ext.notifications.Notification;
import fr.brouillard.oss.commonmark.ext.notifications.NotificationsExtension;
import org.commonmark.Extension;
import org.commonmark.ext.autolink.AutolinkExtension;
import org.commonmark.ext.gfm.strikethrough.StrikethroughExtension;
import org.commonmark.ext.gfm.tables.TableBlock;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.ins.InsExtension;
import org.commonmark.ext.task.list.items.TaskListItemsExtension;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.AttributeProviderContext;
import org.commonmark.renderer.html.AttributeProviderFactory;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.List;
import java.util.Set;

public class MarkdownUtil {
    public static String parseMarkdownToHtml(String markdownText) {
        if (markdownText == null || "".equals(markdownText)) {
            return """
                    <h1 contenteditable='true' ></h1>
                    """;
        }
        Extension notificationExtension = NotificationsExtension.create()
                .withClassMapper((n) -> {
                    return n == Notification.ERROR ? "alert alert-danger" : "alert alert-" + n.name().toLowerCase();
                });

        Set<Extension> extensions = Set.of(
                TablesExtension.create(),   // 表格
                AutolinkExtension.create(),   // 自动链接
                InsExtension.create(),   // 下划线
                TaskListItemsExtension.create(),   // 任务列表
                //NotificationsExtension.create(),   // 第三方扩展：通知/警告段落 https://github.com/McFoggy/commonmark-ext-notifications
                notificationExtension,
                StrikethroughExtension.create())    // 删除线
        ;

        Parser parser = Parser.builder()
                .extensions(extensions)
                .build();
        HtmlRenderer renderer = HtmlRenderer.builder()
                .extensions(extensions)
                .attributeProviderFactory(new AttributeProviderFactory() {
                    public AttributeProvider create(AttributeProviderContext context) {
                        return new NodeAttributeProvider();
                    }
                })
                .build();
        Node document = parser.parse(markdownText);
        String render = renderer.render(document);
        System.out.println("render = " + render);
        return render;
    }
}